package net.caixiaomi.info.life;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.sobot.chat.utils.VersionUtils;

import net.caixiaomi.info.MainActivity;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.model.UpdateEntity;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.service.DownLoadService;
import net.caixiaomi.info.service.Update;
import net.caixiaomi.info.util.ToastUtil;

import java.util.List;

import retrofit2.Call;

/**
 * Created by suntian on 2018/8/3.
 */

public class DownLoadPresenter {

    private static final int recommend = 2;
    private static final int force = 3;

    private Context mContext;
    private UpdateDialog updateDialog;
    private UpdateEntity entity;
    /**
     * 获取赛事列表
     */
    private void getUpdate() {
        JSONObject params = new JSONObject();
        params.put("channel", AppHelper.getChanel(mContext));
        params.put("version", VersionUtils.getVersionName(mContext));
//        params.put("version", "4.0.0");
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UpdateEntity>> updateCall = requestService.getUpdate(params);
        updateCall.enqueue(new ResponseCallback<BaseCallModel<UpdateEntity>>(mContext) {

            @Override
            public void onSuccess(BaseCallModel<UpdateEntity> data) {
                if(data!=null){
                    entity=data.data;
//                    entity.setType("0");
                    updateDialog(entity);
                    registerUpdateBroadcast();
                }
            }

            @Override
            public void onFail(ResponseError error) {
//                ToastUtil.s(error.getMessage());
                mCallback.getStatus("2",error.getMessage());    //2不需要升级
            }

            @Override
            public void onError() {
            }
        });
    }

    public void init(Context context,callback callback){
        mCallback=callback;
        mContext=context;
        getUpdate();
    }

    public callback mCallback;

    public interface callback{
        public void getStatus(String type,String message);
    }

    private void updateDialog(final UpdateEntity update) {
        if (updateDialog == null) {
            updateDialog = new UpdateDialog(mContext);
        }
        String updateLog="";
        if(update.getUpdateLogList()!=null){
            for (int i = 0; i < update.getUpdateLogList().size(); i++) {
                updateLog=updateLog+update.getUpdateLogList().get(i);
                if(i!=update.getUpdateLogList().size()-1){
                    updateLog=updateLog+"\n";
                }
            }
        }

        final boolean isCanCancel=TextUtils.equals(update.getType(),"0");
        updateDialog.setContent(update.getVersion(),updateLog);
        updateDialog.setOneButton(!isCanCancel);
        updateDialog.show();
        updateDialog.setCancelable(isCanCancel);
        updateDialog.setDialogClickListener(new BaseDialogClickListener() {
            @Override
            public void onLeftBtnClick(View view) {
                if(isCanCancel){
                    updateDialog.dismiss();
                }else{
//                    mContext.finish();
                }

            }

            @Override
            public void onRightBtnClick(View view) {
                Intent intent = new Intent(mContext, DownLoadService.class);
//                update.url="https://static.caixiaomi.net/softs/app-armeabi-v7a-release.apk";
                intent.putExtra(DownLoadService.UPDATE_KEY,update);
                mContext.startService(intent);
//                if(isCanCancel){
//                    updateDialog.dismiss();
//                }
            }
        });
        updateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                Activity act= (Activity) mContext;
                WindowManager.LayoutParams lp = act.getWindow().getAttributes();
                lp.alpha = (float) 1; //0.0-1.0
                act.getWindow().setAttributes(lp);
            }
        });
        Activity act= (Activity) mContext;
        WindowManager.LayoutParams lp = act.getWindow().getAttributes();
        lp.alpha = (float) 0.2; //0.0-1.0
        act.getWindow().setAttributes(lp);
    }

    private void registerUpdateBroadcast(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownLoadService.action);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(updateCastReceiver,filter);
    }

    BroadcastReceiver updateCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent != null){
                long count = intent.getLongExtra(DownLoadService.count,0);
                long currentCount = intent.getLongExtra(DownLoadService.current_count,0);
                boolean done = intent.getBooleanExtra(DownLoadService.isFish,false);
                //LLog.i("count = " + count + " currentCount = " + currentCount + " done = " + done);
                updateDialog.setProgressBar(currentCount,count);
                if(done){
                    LocalBroadcastManager.getInstance(mContext).unregisterReceiver(this);
                    updateDialog.dismiss();
                    if(TextUtils.equals(entity.getType(),"1")){
                        Activity act= (Activity) mContext;
                        act.finish();
                    }
                }
            }
        }
    };

}
